<template>
	<uni-popup v-if="loaded" ref="popup" type="bottom" :safeArea="safeArea" backgroundColor="#fff">
		<uni-nav-bar :title="$t('modify')" :border="false" :rightText="$t('submit')" left-icon="left" @clickLeft="close" @clickRight="handleModifyClick" />
		<scroll-view class="modify-form full-width" scroll-y="true">
			<uni-forms v-if="loaded" ref="form" :modelValue="formData" :rules="rules" :label-width="80" label-align="left" label-position="top">
				<uni-forms-item :label="$t('defect.name')" name="projectName" required>
					<uni-easyinput type="text" v-model="formData.projectName" :placeholder="$t('defect.enter-name')" maxlength="128" />
				</uni-forms-item>
				<uni-forms-item :label="$t('describe')" name="remake">
					<uni-easyinput type="textarea" autoHeight v-model="formData.remake" :placeholder="$t('defect.enter-describe').toString()" maxlength="65535"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item :label="$t('image')" name="imgUrls">
					<upload-image :limit="1" v-model="projectIconUrl" />
				</uni-forms-item>
			</uni-forms>
		</scroll-view>
	</uni-popup>
</template>

<script>
	import config from '@/config'
	import { makeDefect } from "@/api/ai/AiDefect"
	import { updateProject } from "@/api/system/project"
	import UploadImage from "@/components/upload-image/index.vue"
	
	/** 开启对话框 */
	export default {
		name: 'ModifyProjectPopup',
		components: { UploadImage },
		data() {
			return {
				projectIconUrl: [],
				formData: {
					moduleId: 0,
					imgUrls: '',
					annexUrls: '',
					handleBy: []
				},
				rules: {
					defectName: {
						rules: [{
							required: true,
							errorMessage: this.$i18n.t('defect.defect-name-cannot-empty'),
						}]
					},
				},
			}
		}, 
		props: {
			safeArea: {
				type: Boolean,
				default: true
			}
		},
		computed: {
			/** UI是否加载完成 */
			loaded: function() {
				return this.$i18n.locale?true:false;
			},
		},
		methods: {
			/** 打开弹簧 */
			open(project) {
				this.formData = {...project};
				this.projectIconUrl = this.projectIcon(project);
				if(this.$refs.popup) {
					this.$refs.popup.open('bottom');
				}
			},
			/** 关闭弹框 */
			close() {
				this.$refs.popup.close();
			},
			/** 处理修改项目 */
			handleModifyClick() {
				this.$refs.form.validate().then(valid => {
					updateProject(this.formData).then(res => {
						this.$modal.msgSuccess(this.$i18n.t('modify-success'));
						this.close();
						this.$emit('input', this.formData);
					}).catch(err=>{
						uni.showToast({
							title: err
						})
					});
				}).catch(err=>{
					uni.showToast({
						title: err
					})
				});
			},
			/** 获取项目图标 */
			projectIcon(project) {
				const regex = /^(https?:\/\/[^\/?#:]+(?::\d+)?)/;
				const match = config.baseUrl.match(regex);
				const url = match ? match[1] : '';
				return project.projectIcon?[url + project.projectIcon]:[];
			},
		}
	}
</script>

<style lang="scss" scoped>
	.modify-form {
		padding: 0 40rpx;
		height: 70vh;
		margin: 0;
	}
</style>